package com.funtl.itoken.service.sso.service.impl;

import com.funtl.itoken.common.domain.TbSysUser;
import com.funtl.itoken.common.utils.MapperUtils;
import com.funtl.itoken.service.sso.mapper.TbSysUserMapper;
import com.funtl.itoken.service.sso.service.LoginService;
import com.funtl.itoken.service.sso.service.consumer.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {

    @Autowired
    private TbSysUserMapper tbSysUserMapper;

    @Autowired
    private RedisService redisService;

    @Override
    public TbSysUser login(String loginCode, String plantPassword) {
        TbSysUser tbSysUser = null;

        String json = redisService.get(loginCode);
        if (StringUtils.isEmpty(json)) {

            Example example = new Example(TbSysUser.class);
            example.createCriteria().andEqualTo("loginCode", loginCode);

            tbSysUser = tbSysUserMapper.selectOneByExample(example);
            if (tbSysUser == null) {
                return null;
            }
            String password = tbSysUser.getPassword();

            String storePassword = DigestUtils.md5DigestAsHex(plantPassword.getBytes());
            if (!password.equals(storePassword)) {
                return null;
            }
            try {
                redisService.put(loginCode, MapperUtils.obj2json(tbSysUser), 24*60*60);
            } catch (Exception e) {
                e.printStackTrace();
            }

        } else {
            try {
                tbSysUser = MapperUtils.json2pojo(json, TbSysUser.class);
            } catch (Exception e) {
                log.warn("触发熔断，{}",e.getMessage() );
                // e.printStackTrace();
            }
        }


        return tbSysUser;
    }
}
